package br.com.travesso.security.dao;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBHelper {

	private Connection connection;

	public DBHelper(String dataSourceJndiName) {
		createConnection(dataSourceJndiName);
	}

	private void createConnection(String dataSourceJndiName) {
		Context context;
		DataSource ds;
		try {
			context = new InitialContext();
			Context envContext = (Context) context.lookup("java:comp/env");
			ds = (DataSource) envContext.lookup(dataSourceJndiName);
			connection = ds.getConnection();
			connection.setAutoCommit(false);
		} catch (Exception e) {
			e.printStackTrace();
			connection = null;
		}
	}

	/**
	 * Fecha a conexão criada
	 */
	public void closeConnection() {
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Connection getConnection() {
		return connection;
	}
}
